package common.msg;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.Message;
import mobile.game.core.support.SysException;

public class MsgIds {
	public static final int TestMsg = 10001;
	public static final int CSGetVersion = 20001;
	public static final int SCGetVersion = 20002;
	
	//消息CLASS与消息ID的对应关系<消息class, 消息ID>
	private static final Map<Class<? extends Message>, Integer> classToId = new HashMap<>();
	//消息ID与消息CLASS的对应关系<消息ID, 消息class>
	private static final Map<Integer, Class<? extends Message>> idToClass = new HashMap<>();
	
	static {
		//初始化消息CLASS与消息ID的对应关系
		initClassToId();
		//初始化消息ID与消息CLASS的对应关系
		initIdToClass();
	}
	
	/**
	 * 获取消息ID
	 * @param clazz
	 * @return
	 */
	public static int getIdByClass(Class<? extends Message> clazz) {
		return classToId.get(clazz);
	}
	
	/**
	 * 获取消息CLASS
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getClassById(int msgId) {
		return (T) idToClass.get(msgId);
	}
	
	/**
	 * 获取消息名称
	 * @param clazz
	 * @return
	 */
	public static String getNameById(int msgId) {
		try {
			return idToClass.get(msgId).getSimpleName();
		} catch (Exception e) {
			throw new SysException(e, "获取消息名称是发生错误：msgId={0}", msgId);
		}
	}
	
	/**
	 * 初始化消息CLASS与消息ID的对应关系
	 */
	private static void initClassToId() {
		classToId.put(Test.TestMsg.class, TestMsg);
		classToId.put(Demo.CSGetVersion.class, CSGetVersion);
		classToId.put(Demo.SCGetVersion.class, SCGetVersion);
	}
	
	/**
	 * 初始化消息ID与消息CLASS的对应关系
	 */
	private static void initIdToClass() {
		idToClass.put(TestMsg,Test.TestMsg.class);
		idToClass.put(CSGetVersion,Demo.CSGetVersion.class);
		idToClass.put(SCGetVersion,Demo.SCGetVersion.class);
	}
	/**
	 * 根据消息id解析消息
	 */
	public static Message parseFrom(int msgId, CodedInputStream s) throws IOException{
		switch(msgId){
			case TestMsg:
				return Test.TestMsg.parseFrom(s);
			case CSGetVersion:
				return Demo.CSGetVersion.parseFrom(s);
			case SCGetVersion:
				return Demo.SCGetVersion.parseFrom(s);
		}
		return null;
	}
}

